// 监听对话
import bot from "../init/bot.js"
import {gptReply} from "../utils/reply.js"
import {initGame,endGame,checkGameStatus,getGameResult} from  "../games/index.js" // 引入小游戏功能
import {getPic,getPicSearch,dogDic,getBq,getLearn,handleGetSongs,handleCheckPost,handleRestart} from  "../functions/index.js" // 其他功能
import { getUrl } from "../utils/fs.js"

import delay  from "../utils/delay.js";
export default async function onMessage(msg) {
  const room = msg.room(); // 是否是群消息
  const contact = msg.talker(); // 发消息人
  const replyer = room || contact

      try{
        // if(!contact.history) contact.history = []
        let content = msg.text().trim(); // 消息内容
        if( msg.type()==0){
          return false
        }
        const alias = await contact.alias() || await contact.name(); // 发消息人备注
        const friend = await contact.friend()
        const isText = msg.type() === bot.Message.Type.Text;
        const mentionSelf = await msg.mentionSelf()
        if (msg.self() ) {
          return;
        }
        // if(room){
    
        //   if (fileTypeList.includes(msg.type())) {
        //     const fileBox = await msg.toFileBox()
        //     console.info(`Saving file {$fileBox.name}...`)
        //     await fileBox.toFile(getUrl(fileBox.name)) 
        //     setTimeout(() => {
        //     removeFile(getUrl(fileBox.name))
              
        //     }, 3000);
        //   //   console.log(fileBox.name)
        //   //  saveFile(fileBox,'1.png')
        //   }
        //   return
        // }
        // 群里的所有消息
     
          // 此人上次跟我的对话
        if(room ){
          // 记录历史记录
          room.history =  room.history || []
          if( room.history.length>=10){
            room.history.shift()
          }
          room.history.push(msg)
        
        
        if (room  && mentionSelf) {
       
          if( !room.history){
            room.history = []
          }
          
          content = content.replace('@海公牛', '')
          if(!content){
            const lastRes = await handleLastSay(room,contact,msg)
            if(!lastRes){
              room.say `${contact} 你问的这是什么问题啊？`
              return
            }
            content = lastRes
            // room.say `${contact} 什么事？你好像没说话`
            // return
          }
          if (/」|「/.test(content)) {
            return
          }
          console.log(contact)
          // 在这里先判断游戏是否在进行，判断内容跟游戏是不是有关系
          if(room.game){
          console.log("有游戏进行优先判断游戏内容")
          await getGameResult(content,room,contact)
          return
            //有游戏进行优先判断游戏内容
          }
          sayMessage({content,room,contact,msg})
        } }
        else{
          if (alias == 'bossName' || friend) {
            isText ?   sayMessage({ room, content, contact,msg }) : messageFile(msg)
          }
        }
        // if(room && !mentionSelf){
        //   console.log('与我无关')
        // contact.lastMention  ?  contact.lastMention=false  :null
        // }
      }catch(e){
        console.log(e)
        console.log('消息错误')
        room.say `你说的我没听明白呢，要不你再说一遍？`
      }
  
  }
  async function sayMessage({ room, content, contact,msg }) {
    if (!room) {
      const res = await gptReply(content, room, contact)
      contact.say(res)
    }else{
      if(/人生重开/.test(content)){
        delay(1000)
         handleRestart(content,room,msg)
        return
      }
      if(/快递/.test(content)){
        await handleCheckPost(content,room,msg)
        return
      }

      // //  点歌
   
      // if(/歌曲分享|点歌/.test(content)){
      //   await handleGetSongs(content,room,msg)

      //   return
      // }
       //表情包
       if(/我爱学习|学习笔记/.test(content)){
         getLearn(room)
        return
      }
      //表情包
      if(/表情包|搜表情/.test(content)){
        const res = await getBq(content,room)
        return
      }
      // 舔狗
      if(/舔狗日记/.test(content)){
        const res = await dogDic()
        if(res){
          console.log(res)
          room.say(res?.result?.content)
        }
        return
      }
      if(/生成图片|制作图片|搜索图片|制图/.test(content)){
        getPicSearch(room,content,contact)
        return
      }
      // console.log(/福利图片 | 美女图片/.test(content))
      if(/福利图片|美女图片|福利/.test(content)){
        // await room.say`${contact} 好好好，这就给你找几张福利图片……*_*`
        setTimeout(() => {
        getPic(room,content)
        }, 1500);
        return
      }

    // 
      const noGptRply = ['猜数字','不玩了','成语接龙']
      const index = noGptRply.findIndex(it=>{
        if(content.indexOf(it)>-1) return it
      })
      console.log(index)
      const manage = index!==-1 ?  noGptRply[index] : null
      //其他的一些小游戏
      const manageList = {
    
         "猜数字":(room,content,contact)=>{
          initGame(room,'1',contact)
         },
         "成语接龙":()=>{
          initGame(room,'2',contact)
         },
         "不玩了":(room)=>{
          endGame(room)
         },
 
        'default':()=>{}
      }
      manage ?  manageList[manage]?.(room,content,contact) : gptReply(content, room, contact)

    }
  }
  const messageFile = async (message)=>{

    const fileTypeList = [
      bot.Message.Type.Attachment,
      bot.Message.Type.Audio,
      bot.Message.Type.Image,
      bot.Message.Type.Video,
      bot.Message.Type.Emoticon,
    ]
    console.log(message.type())
    if (fileTypeList.includes(message.type())) {
      const fileBox = await message.toFileBox()
      console.log(fileBox)
      const rs = await fileBox.toFile("./files/"+fileBox._name)
      console.log(rs)
      const fileName = await getUrl(fileBox._name)
      console.log(getUrl(fileBox._name))
      return getUrl(fileBox._name)
    }
  }
// 处理上一句话的消息
  const handleLastSay =(room,contact)=>{
    return new Promise((resolve,roject)=>{
      if(room.history && room.history.length ){
        let index=room.history.length-2
        const msg = room.history[index] || ''
        if(!msg) resolve('');
        const type = msg?.type()
        console.log(msg.type())
        if(type==7 || type==5){
          let content = msg.text()?.trim() || ''
          content = content.replace('@海公牛',"")
          resolve(content)
        }else{
          resolve('')
          const fileName = messageFile(msg)
          console.log(fileName)
        }
   
      }else{
        resolve(false)
      }
      
    }) 
  }

  
